package org.linphone;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import org.linphone.assistant.RemoteProvisioningActivity;
import org.linphone.http.HtmlService;
import org.linphone.mediastream.Version;
import org.linphone.tutorials.TutorialLauncherActivity;

import static android.content.Intent.ACTION_MAIN;

/*在主界面调用这个service直接启动Linphone的service别人打电话直接可以接收,并且保证不被杀死*/
public class LinphoneLaucherService extends Service {
    private static final String TAG = "LinphoneLaucherService";
    private Handler mHandler;
    private ServiceWaitThread mThread;
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate: "+"start");
        mHandler = new Handler();
        initLinophoneService();

        //开启SIP账号与广播配置<-- 从submain的主界面直接进入进行配置
        Intent httpService = new Intent(this, HtmlService.class);
        startService(httpService);

    }

    private void initLinophoneService() {
        if (LinphoneService.isReady()){
            onServiceReady();
        }else {
            startService(new Intent(ACTION_MAIN).setClass(this, LinphoneService.class));
            mThread = new ServiceWaitThread();
            mThread.start();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand: "+"start");
        initLinophoneService();
        return START_STICKY;
    }

    protected void onServiceReady() {
        // We need LinphoneService to start bluetoothManager
        if (Version.sdkAboveOrEqual(Version.API11_HONEYCOMB_30)) {
            BluetoothManager.getInstance().initBluetooth();
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    private class ServiceWaitThread extends Thread {
        public void run() {
            while (!LinphoneService.isReady()) {
                try {
                    sleep(30);
                } catch (InterruptedException e) {
                    throw new RuntimeException("waiting thread sleep() has been interrupted");
                }
            }
            mHandler.post(new Runnable() {
                @Override
                public void run() {//主线程
                    onServiceReady();
                }
            });
            mThread = null;
        }
    }

    @Override
    public void onDestroy() {
       //如果service被回收则重新启动
        Intent intent = new Intent();
        //intent.setClassName("com.sxygsj.newsubmain", "com.sxygsj.newsubmain.activities.MainActivity");
       // intent.setClassName("com.sxygsj.submain", "com.sxygsj.submain.MainActivity");
        intent.setClassName("com.sxygsj.newsubmain", "com.sxygsj.newsubmain.activities.MainActivity");
        startActivity(intent);
        super.onDestroy();
    }
}
